<template>
  <div class="book-detail-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item><a href="/front">首页</a></el-breadcrumb-item>
      <el-breadcrumb-item style="font-weight: bold">{{ categories.find(v => v.id == bookInfo.categoryId)?.name }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ bookInfo.name }}</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 图书基本信息 -->
    <el-card class="book-base-info">
      <div class="book-header">
        <div class="book-cover">
          <img :src="bookInfo.cover" :alt="bookInfo.name" class="cover-img">
        </div>
        <div class="book-main-info">
          <h1 class="book-title">{{ bookInfo.name }}</h1>
          <p class="book-subtitle">{{ bookInfo.descr }}</p>

          <div class="book-meta">
            <div class="meta-item">
              <span class="meta-label">作者：</span>
              <span class="meta-value">{{ bookInfo.author }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">出版社：</span>
              <span class="meta-value">{{ bookInfo.publisher }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">出版日期：</span>
              <span class="meta-value">{{ bookInfo.date }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">ISBN：</span>
              <span class="meta-value">{{ bookInfo.isbn }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">库存：</span>
              <span class="meta-value">{{ bookInfo.store }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">借阅次数：</span>
              <span class="meta-value">{{ bookInfo.borrowCount }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">分类：</span>
              <el-tag type="primary" class="category-tag">
                {{ categories.find(v => v.id == bookInfo.categoryId)?.name }}
              </el-tag>
            </div>
          </div>

          <div class="book-actions">
            <el-button type="primary" size="medium" class="main-action-btn" @click="handleBorrow">
              <i class="el-icon-check"></i> {{ '可借阅' }}
            </el-button>
            <el-button :type="isCollect ? 'danger' : 'warning'" size="medium" class="action-btn" icon="el-icon-star-off" @click="toggleFavorite" title="收藏/取消收藏">
              {{ isCollect ? '已收藏' : '收藏' }}
            </el-button>
          </div>
        </div>

      </div>
    </el-card>

    <!-- 内容标签页 -->
    <el-tabs v-model="activeTab" class="content-tabs" type="card">
      <!-- 图书简介 -->
      <el-tab-pane label="图书简介" name="description">
        <el-card>
          <div class="description-content">
            <p class="rich-text-content w-e-text" v-html="bookInfo.content"></p>
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 馆藏信息 -->
      <el-tab-pane label="评论信息" name="collection">
        <el-card class="content-container-margin">
          <h3 class="comment-title">评论区 ({{ commentTotal }})</h3>

          <!-- 顶级评论输入框（仅登录显示） -->
          <div class="top-comment-input" v-if="user.id">
            <el-input type="textarea" v-model="topCommentContent" placeholder="写下你的评论..." rows="3" class="top-textarea"></el-input>
            <el-button type="primary" class="submit-top-btn" @click="submitTopComment">发布评论</el-button>
          </div>
          <div class="login-tip" v-else>
            <el-button type="text" @click="$router.push('/login')">登录后可发表评论</el-button>
          </div>

          <!-- 评论列表（渲染顶级评论，子评论递归显示） -->
          <div class="comment-list" v-if="commentTree.length > 0">
            <comment-item v-for="comment in commentTree" :key="comment.id" :comment="comment" :fid="bookInfo.id" :is-login="user.id" :current-user="user" @refresh-comment="loadCommentTree"></comment-item>
          </div>

          <!-- 无评论提示 -->
          <div class="no-comment" v-if="commentTree.length === 0 && isCommentLoaded">
            暂无评论，快来抢沙发~
          </div>
        </el-card>
      </el-tab-pane>

    </el-tabs>

    <el-dialog title="信息" :visible.sync="dialogFormVisible" width="30%" :close-on-click-modal="false">
      <el-form label-width="100px" style="padding-right: 40px" :model="form" :rules="borrowRules" ref="borrowFormRef">
        <el-form-item prop="startDate" label="借阅日期">
          <el-date-picker style='width:100%' v-model="form.startDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item prop="endDate" label="应还日期">
          <el-date-picker style='width:100%' v-model="form.endDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="borrow">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CommentItem from '../../conponents/CommentItem.vue'

export default {
  name: 'BookDetail',
  components: {
    CommentItem // 注册评论组件
  },
  data() {
    return {
      id: this.$route.query.id,
      // 激活的标签页
      activeTab: 'description',
      // 图书基本信息
      bookInfo: {},
      commentTree: [],        // 评论树形结构
      topCommentContent: '',  // 顶级评论内容
      commentTotal: 0,        // 评论总数
      isCommentLoaded: false, // 评论是否加载完成
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      isCollect: false,
      categories: [],
      dialogFormVisible: false,
      form: {},
      // 借阅表单校验规则
      borrowRules: {
        startDate: [{ required: true, message: '请选择借阅日期', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择应还日期', trigger: 'change' }]
      }
    };
  },
  created() {
    this.load()
    this.loadCategory()
  },
  methods: {
    handleBorrow(){
      if (typeof this.user.name === 'undefined'){
        this.$notify.warning({title: '成功', message: '请登录', showClose: false, duration: 2000});
        this.$router.push('/login')
        return;
      }
      this.form = {}
      this.dialogFormVisible = true
    },
    borrow(){
      if (typeof this.user.name === 'undefined'){
        this.$notify.warning({title: '成功', message: '请登录', showClose: false, duration: 2000});
        this.$router.push('/login')
        return;
      }
      this.$refs.borrowFormRef.validate((isValid) => {
        if (!isValid) return;
        let data = {
          userId: this.user.id,
          name: this.bookInfo.name,
          bookId: this.bookInfo.id,
          startDate: this.form.startDate,
          endDate: this.form.endDate
        }
        this.$request({
          method: 'POST',
          url: "/borrow",
          data: data
        }).then(res => {
          if (res.code === '200') {
            this.$notify.success({title: '成功', message: '借阅成功', showClose: false, duration: 2000});
            this.dialogFormVisible = false
          } else {
            this.$notify.warning({title: '成功', message: res.msg, showClose: false, duration: 2000});
          }
          this.load()
        })
      })


    },
    toggleFavorite() {
      if (typeof this.user.name === 'undefined'){
        this.$notify.warning({title: '成功', message: '请登录', showClose: false, duration: 2000});
        this.$router.push('/login')
        return;
      }
      let data = {
        userId: this.user.id,
        bookId: this.bookInfo.id
      }
      this.$request({
        method: 'POST',
        url: "/collect",
        data: data
      }).then(res => {
        if (res.code === '200') {
          this.$notify.success({title: '成功', message: '收藏成功', showClose: false, duration: 2000});
          this.isCollect = false;
        } else {
          this.isCollect = true;
          this.$notify.warning({title: '成功', message: res.msg, showClose: false, duration: 2000});
        }
        this.load()
      })
    },
    loadCategory() {
      this.$request.get("/category").then(res => {
        this.categories = res.data
      })
    },
    load() {
      this.$request.get("/book/" + this.id).then(res => {
        this.bookInfo = res.data
        this.isCollect = this.bookInfo.isCollect || false
          // 图书加载完成后加载评论
          this.loadCommentTree()
      })
    },
    loadCommentTree() {
      if (!this.bookInfo.id) return; // 确保图书ID存在
      this.$request({
        url: '/comment/tree',
        method: 'GET',
        params: { fid: this.bookInfo.id } // fid=图书ID
      }).then(res => {
        if (res.code === '200') {
          this.commentTree = res.data;
          this.commentTotal = this.calcCommentTotal(res.data); // 统计评论总数
        }
        this.isCommentLoaded = true;
      });
    },
    // 新增2：递归计算评论总数（含所有子评论）
    calcCommentTotal(comments) {
      let count = comments.length;
      comments.forEach(comment => {
        if (comment.children && comment.children.length > 0) {
          count += this.calcCommentTotal(comment.children);
        }
      });
      return count;
    },
    submitTopComment() {
      if (!this.topCommentContent.trim()) {
        this.$notify.warning({ title: '提示', message: '请输入评论内容' });
        return;
      }
      const params = {
        content: this.topCommentContent.trim(),
        fid: this.bookInfo.id,  // 关联图书ID
        pid: 0,                // 顶级评论：pid=0
        level: 1,                // 顶级评论：level=1
        userId: this.user.id   // 当前登录用户ID
      };
      this.$request({
        url: '/comment',
        method: 'POST',
        data: params
      }).then(res => {
        if (res.code === '200') {
          this.$notify.success({ title: '成功', message: res.msg });
          this.topCommentContent = '';
          this.loadCommentTree(); // 刷新评论列表
        } else {
          this.$notify.error({ title: '失败', message: res.msg });
        }
      });
    },
  }
};
</script>

<style scoped>
.book-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
}

/* 图书基本信息样式 */
.book-base-info {
  margin-bottom: 20px;
  overflow: hidden;
}

.book-header {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.book-cover {
  flex: 0 0 200px;
}

.cover-img {
  width: 250px;
  height: 300px;
  border-radius: 4px;
  /*box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);*/
}

.book-main-info {
  flex: 1;
  min-width: 300px;
  margin-left: 20px;
}

.book-title {
  font-size: 24px;
  margin: 0 0 10px;
  color: #333;
}

.book-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0 0 20px;
  font-weight: normal;
  line-height: 2;
}

.book-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px 30px;
}

.meta-item {
  display: flex;
  align-items: center;
  min-width: 250px;
}

.meta-label {
  color: #666;
  width: 80px;
  flex-shrink: 0;
}

.meta-value {
  color: #333;
  line-height: 1.5;
}

.category-tag {
  margin-right: 8px;
  cursor: pointer;
}

.book-actions {
  margin-top: 20px
}

.main-action-btn {
  width: 20%;
}

.action-btn {
  width: 20%;
}

/* 内容标签页样式 */
.content-tabs {
  margin-bottom: 30px;
}

/* 图书简介样式 */
.description-content {
  padding: 10px 0;
}

.content-container-margin {
  margin: 10px auto;          /* 上下外边距10px，水平居中 */
  padding: 6px;               /* 内边距6px */
}

.comment-title {
  font-size: 16px;            /* 字体大小16px */
  font-weight: 600;           /* 中等加粗 */
  color: #333;                /* 深灰色文字 */
  margin: 10px 0 20px;        /* 上10px，下20px，左右0 */
  padding-bottom: 8px;        /* 底部内边距8px */
  border-bottom: 1px solid #eee; /* 底部细线分隔 */
}

.top-comment-input {
  display: flex;              /* 弹性布局 */
  flex-direction: column;     /* 垂直排列 */
  margin-bottom: 20px;        /* 底部外边距20px */
}

.top-textarea {
  margin-bottom: 10px;        /* 文本域底部间距10px */
  resize: none;               /* 禁止手动调整大小 */
}

.submit-top-btn {
  align-self: flex-end;       /* 按钮靠右对齐 */
}

.login-tip {
  margin: 20px 0;             /* 上下外边距20px */
  color: #999;                /* 提示文字浅灰色 */
}

.comment-list {
  margin-top: 20px;           /* 评论列表顶部间距20px */
}

.no-comment {
  text-align: center;         /* 文字水平居中 */
  padding: 40px 0;            /* 上下内边距40px（视觉垂直居中） */
  color: #999;                /* 浅灰色提示 */
  border-radius: 4px;         /* 轻微圆角 */
  margin-top: 20px;           /* 与上方内容间距20px */
}

</style>
